from QQLoginTool.QQtool import OAuthQQ
from django.conf import settings  # 拿到配置项的对象
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status

# Create your views here.
import logging

# 日志记录错误信息
from rest_framework_jwt.settings import api_settings

from carts.utils import merge_cart_cookie_to_redis
from oauth.models import OAuthQQUser
from oauth.serializers import QQAuthUserSerializer
from .utils import generate_save_user_token

logger = logging.getLogger('django')



# url(r'^qq/user/$', views.QQAuthUserView.as_view()),
class QQAuthUserView(APIView):
    """QQ认证用户视图"""
    # GET请求
    def get(self, request):
        """完成QQ的oauth 2.0认证"""
        # 提取code请求参数  http://www.meiduo.site:57892/oauth_callback.html?code=AC404CFA4B95969D9827403A6BE343B0&state=%2F
        code = request.query_params.get('code')
        # code非空判断
        if not code:
            return Response({'message': '没有code'}, status=status.HTTP_400_BAD_REQUEST)
        # 创建OAuthQQ的工具对象
        oauthqq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                          client_secret=settings.QQ_CLIENT_SECRET,
                          redirect_uri=settings.QQ_REDIRECT_URI)
        try:
            # 使用code向QQ服务器请求access_token
            access_token = oauthqq.get_access_token(code)
            # 使用access_token向QQ服务器请求openid
            openid = oauthqq.get_open_id(access_token)
        except Exception as error:
            logger.info(error)
            # 返回响应 ==> 因为源码中没有响应,都是抛出
            return Response({'message': 'QQ服务异常'}, status=status.HTTP_503_SERVICE_UNAVAILABLE)


        """通过上面步骤拿到open_id 然后通过open_id来查此QQ是否绑定过用户"""
        try:
            # 使用openid查询该QQ用户是否在美多商城中绑定过用户
            oauth_model = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist: # 如果数据库中取不到openid,肯定是没有绑定过用户
            # 如果openid没绑定美多商城用户，创建用户并绑定到openid

            # 对openid进行加密之后再响应给前端,前端进行保存,为后面创建用户并绑定到openid做准备
            access_token_openid = generate_save_user_token(openid)

            # 返回响应
            # return Response( data={"access_token": openid} ) 注意: 最好不要这样返回,最好进行加密返回响应
            return Response( data={"access_token": access_token_openid} )


        else:

            # 如果openid已绑定美多商城用户，直接生成JWT token，并返回
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER  # 加载jwt配置中的处理payload的函数(引用)
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER  # 加载生成token的函数(引用)

            # 获取oauthModel关联/绑定的用户模型对象
            # 用户模型对象 = 通过oauth_model模型的外键来获取
            user = oauth_model.user
            payload = jwt_payload_handler(user)  # 传入用户对象来生成payload
            token = jwt_encode_handler(payload)  # 通过上面运算出来的值进行加盐,然后生成token


            # 响应数据
            response = Response({
                'user_id': user.id,
                'username': user.username,
                'token': token
            })

            # 要做购物车合并
            return merge_cart_cookie_to_redis(request, user, response)

    # 前端写死路由, 所以写在这
    # POST 请求
    def post(self, request):
        """openid绑定用户"""
        # 1.创建序列化器对象
        serializer = QQAuthUserSerializer(data=request.data)
        # 2.数据校验验证
        serializer.is_valid(raise_exception=True)
        # 3.保存
        user = serializer.save()

        # 创建token并然绑定在user模型上.方便响应出去
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER  # 加载jwt配置中的处理payload的函数
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER  # 加载生成token的函数

        payload = jwt_payload_handler(user)  # 传入用户对象来生成payload
        token = jwt_encode_handler(payload)

        # 响应数据
        response = Response({

            'user_id': user.id,
            'username': user.username,
            'token': token

        })

        # 要做购物车合并
        return merge_cart_cookie_to_redis(request, user, response)


class QQAuthURLView(APIView):
    """QQ跳转二维码视图"""

    def get(self, request):
        """返回QQ扫码url"""
        # 获取next参数的来源
        next = request.query_params.get('next')
        # 非空判断
        if not next:
            next = '/'  # next没有值表示直接主页登录

        # # QQ登录参数
        # QQ_CLIENT_ID = '101514053'
        # QQ_CLIENT_SECRET = '1075e75648566262ea35afa688073012'
        # QQ_REDIRECT_URI = 'http://www.meiduo.site:8080/oauth_callback.html'
        # 创建OAuthQQ的工具对象
        oauthqq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                          client_secret=settings.QQ_CLIENT_SECRET,
                          redirect_uri=settings.QQ_REDIRECT_URI,
                          state=next)

        # 调用SDK中的方法获取到拼接好的扫码url
        login_url = oauthqq.get_qq_url()

        # 响应出来 给前端用来跳转
        return Response({'login_url': login_url})